﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using MyLib;
using System.Web;

using Portal.Entity;
using Portal.Interface;

namespace Portal.Logic
{
    /// <summary>
    /// 权限管理
    /// </summary>
    public class SecurityLogic
    {
        /// <summary>
        /// 获取当前用户有权限的资源
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public List<ResourceEntity> GetSecurityList(string loginName)
        {
            List<ResourceEntity> results = new List<ResourceEntity>();
            ResourceLogic res = new ResourceLogic();
            List<ResourceEntity> list= res.GetResourceList();
            string userName = loginName;
            if (loginName.Split('\\').Length > 1)
            {
                userName = loginName.Split('\\')[1];
            }
            if (ConfigurationManager.AppSettings["AdminAccount"].ToUpper() == userName.ToUpper()) //超级管理员，不判断权限
            {
                return list;
            }
            results = list.FindAll(p => p.TYPE == "Menu" && p.EXT06 == "1"); //Ext06=1的菜单，不判断权限
            IOrg org = ServiceContainer.Instance().GetService<IOrg>();
            UserEntity user= org.GetUserEntity(loginName);
            
            //获取用户所在的组
            List<ResourceEntity> groups = org.GetUserGroups(loginName);
            string group = "-1,";
            foreach (ResourceEntity g in groups)
            {
                group += g.RESOURCEID.ToString() + ",";
            }
            group = group.TrimEnd(',');

            //获取用户所在的部门
            List<ResourceEntity> depts = org.GetUserDepartments(loginName);
            string dept = "-1,";
            foreach (ResourceEntity d in depts)
            {
                dept += d.RESOURCEID.ToString() + ",";
            }
            dept = dept.TrimEnd(',');
            //获取该用户有权限的资源Id
            string userid = user.USERID.ToString();
            Hashtable table=new Hashtable();
            table.Add("userId", userid);
            table.Add("dept", dept);
            table.Add("group", group);
            List<ResourceRelationEntity> relations = DataAccess.Instance("BizDB").GetList<ResourceRelationEntity>("SecurityLogic_GetSecurityList", table);
            foreach (ResourceRelationEntity relation in relations)
            {
                if (!results.Exists(p => p.RESOURCEID == relation.DESTINATIONID))
                {
                    ResourceEntity ety= list.Find(p => p.RESOURCEID == relation.DESTINATIONID);
                    if (ety != null)
                    {
                        results.Add(ety);
                    }
                }
            }
            
            return results;
        }

        /// <summary>
        /// 判断某个资源释是否有权限
        /// </summary>
        /// <returns></returns>
        public bool CheckSecurity(int resourceId, string loginName)
        {
            List<ResourceEntity> list = GetSecurityList(loginName);
            return list.Exists(p => p.RESOURCEID == resourceId);
        }
        
        /// <summary>
        /// 获取数据权限类型
        /// </summary>
        /// <returns></returns>
        public List<string> GetSecurityTypeList()
        {
            List<string> strs = new List<string>();
            string[] sz = ConfigurationManager.AppSettings["SecurityType"].Split(',');
            foreach (string str in sz)
            {
                strs.Add(str);
            }
            return strs;
        }

        public int SaveSecurity(int resouceId, string name, string strMembers, string strMemberId, List<SecurityMemberEntity> members,string securityType, List<ResourceEntity> objects)
        {
            ResourceRelationLogic relation = new ResourceRelationLogic();
            SerialNoLogic sn=new SerialNoLogic();
            int count = DataAccess.Instance("BizDB").GetEntity<int>("SELECT COUNT(1) FROM COM_RESOURCE WHERE RESOURCEID="+resouceId);
            ResourceEntity ety = new ResourceEntity();
            ety.CNNAME = name;
            ety.ENNAME = name;            
            ety.TYPE = "Security";
            ety.EXT01 = strMembers;
            ety.EXT02= strMemberId;
            ety.ISACTIVE = "1";
            if(resouceId==0)
            {
                resouceId = sn.GetMaxNo("COM_RESOURCE", "RESOURCEID");
            }
            ety.RESOURCEID=resouceId;
            //保存权限名称
            if (count > 0)
            {
                DataAccess.Instance("BizDB").Update("ResourceLogic_Update", ety);
            }
            else
            {
                DataAccess.Instance("BizDB").Insert("ResourceLogic_Insert", ety);
            }

            Hashtable table = new Hashtable();
            table.Add("SOURCEID", resouceId);
            table.Add("SECURITYTYPE", securityType);
            DataAccess.Instance("BizDB").Delete("ResourceRelationLogic_Delete", table);
            //保存授权成员
            foreach (SecurityMemberEntity member in members)
            {
                ResourceRelationEntity relationEty=new ResourceRelationEntity();
                relationEty.SOURCEID=resouceId;
                relationEty.ID = sn.GetMaxNo("COM_RESOURCERELATION","ID");
                relationEty.DESTINATIONID = member.MemberId;
                relationEty.EXT01 = member.MemberType;
                relationEty.RELATIONTYPE = "SecurityMember";
                relation.Save(relationEty);
            }
            //保存授权对象
            foreach (ResourceEntity resource in objects)
            {
                ResourceRelationEntity relationEty = new ResourceRelationEntity();
                relationEty.SOURCEID = resouceId;
                relationEty.ID = sn.GetMaxNo("COM_RESOURCERELATION", "ID");
                relationEty.DESTINATIONID = resource.RESOURCEID;
                relationEty.EXT01 = resource.TYPE;
                relationEty.RELATIONTYPE = "SecurityObject";
                relation.Save(relationEty);
            }

            return resouceId;
        }

        
    }
}
